﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Bymed.RegistrationCodeManager.Service.Shared;
using Miris.HumanMilkAnalyser.Service.Shared;

namespace Miris.HumanMilkAnalyser.Service
{
    public enum GenuineCheckStatus
    {
        Unchecked,
        Passed,
        Failed
    }

    public class GenuineCheckService
    {
        public GenuineCheckStatus CurrentCheckStatus { get; set; }

        public GenuineCheckService()
        {
            CurrentCheckStatus = GenuineCheckStatus.Unchecked;
        }

        /// <summary>
        /// Get the saved the serial number.
        /// </summary>
        /// <returns>The saved serial number.</returns>
        public string GetSerialNumber()
        {
            // Get the minilog file directory full name from config file.
            var localMiniLogFileDirectoryFullName = Path.Combine(Environment.CurrentDirectory, (string)ConfigFileUtility.GetValue(ConfigurationConstant.LocalMiniLogFileDirectoryName));
            var localMiniLogFileFullName = Path.Combine(localMiniLogFileDirectoryFullName, (string)ConfigFileUtility.GetValue(ConfigurationConstant.MiniLogFileName));
            var serialNumber = string.Empty;

            // Check if the minilog exists.
            if (!File.Exists(localMiniLogFileFullName))
            {
                throw new ArgumentException("未找到本地同步的设备数据文件，请联系设备提供商");
            }

            // Open minilog file
            using (var fs = new FileStream(localMiniLogFileFullName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            {
                using (var sr = new StreamReader(fs, Encoding.Default))
                {
                    string currentLine = string.Empty;
                    string[] arrayData = null;

                    while (sr.Peek() != -1)
                    {
                        // Read current line content
                        currentLine = sr.ReadLine();

                        // Check if current line starts with M
                        if (currentLine.StartsWith("M", StringComparison.OrdinalIgnoreCase))
                        {
                            // Convert the data into string array.
                            arrayData = currentLine.Split(',');

                            // Check the Measuring Chamber Number.
                            // Example, AA571100171201100159.
                            serialNumber = arrayData[72];
                            break;
                        }
                    }
                }
            }

            return serialNumber;
        }

        /// <summary>
        /// Gets the first Ethernet Mac Address on current computer.
        /// </summary>
        /// <returns></returns>
        public string GetComputerName()
        {
            return RegistrationCodeManagerUtility.GetFirstEthernetMacAddress();
        }

        /// <summary>
        /// Check the input serial number comes from device is the same as current one.
        /// </summary>
        /// <param name="inputSerialNumber">The input serial number comes from device.</param>
        /// <returns>GenuineCheckStatus</returns>
        public GenuineCheckStatus Check(string inputSerialNumber)
        {
            var storedRegistrationCode = (string)ConfigFileUtility.GetValue(ConfigurationConstant.RegistrationCode);
            var registrationCode = RegistrationCodeManagerUtility.DecryptRegistrationCode(storedRegistrationCode);

            if (registrationCode != null)
            {
                var inputMacAddress = registrationCode.ComputerNumber;
                var inputAuthorisedUsageCount = registrationCode.AuthorisedUsageCount;

                var currentSerialNumber = registrationCode.DeviceNumber;
                var currentMacAddress = GetComputerName();
                var currentAuthorisedUsageCount = GeneralUtility.GetAvailableAuthorisedUsageCount();

                // Check if current Serial Number is the same as the one comes from device as well as the MacAddress.
                if (currentSerialNumber == inputSerialNumber &&
                    currentMacAddress == inputMacAddress &&
                    currentAuthorisedUsageCount <= inputAuthorisedUsageCount &&
                    currentAuthorisedUsageCount != 0)
                {
                    CurrentCheckStatus = GenuineCheckStatus.Passed;
                }
                else
                {
                    CurrentCheckStatus = GenuineCheckStatus.Failed;
                }
            }
            else
            {
                CurrentCheckStatus = GenuineCheckStatus.Failed;
            }

            return CurrentCheckStatus;
        }
    }
}
